/* ************************************************************************ */
/*                                                                          */
/*  Copyright (c)2005 Russell Weir | damonsbane _at_ gmail                  */
/*                                                                          */
/* This library is free software; you can redistribute it and/or            */
/* modify it under the terms of the GNU Lesser General Public               */
/* License as published by the Free Software Foundation; either             */
/* version 3.0 of the License, or (at your option) any later version.       */
/*                                                                          */
/* This library is distributed in the hope that it will be useful,          */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of           */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU        */
/* Lesser General Public License or the LICENSE file for more details.      */
/*                                                                          */
/* ************************************************************************ */

package tzparser;

class RuleSet {
	var name : String;
	var rules : Array<Rule>;

	public function new(name : String) {
		rules = new Array();
		this.name = name;
	}

	public function add(rl : Rule) {
		rules.push(rl);
	}

	public function sort() {
		var sf = function(item1 : Rule, item2 : Rule) : Int {
			if(item1.validFromYear < item2.validFromYear)
				return -1;
			if(item1.validFromYear > item2.validFromYear)
				return 1;

			// same start year. longer running rules come first
			if(item1.until.year > item2.until.year)
				return -1;
			if(item1.until.year < item2.until.year)
				return 1;

			if(item1.until.month < item2.until.month)
				return -1;
			if(item1.until.month > item2.until.month)
				return 1;

			// could check for day of month, but are we really going
			// to collide here?
			return 0;
		}
		rules.sort(sf);
	}

	public function iterator() : Iterator<Rule> {
		return rules.iterator();
	}

	public function toString() : String {
		var sb = new StringBuf();
		var it = rules.iterator();
		for(i in it) {
			sb.add(i);
			if(it.hasNext())
				sb.add("\n");
		}
		return sb.toString();
	}
}
